package com.chen.common.satoken.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.chen.root.base.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 全局异常处理器
 * </p>
 *
 * @author long
 * @date 2023-05-14
 */
@Slf4j
@ApiIgnore
@Order(0)
@RestController
@RestControllerAdvice
public class SaTokenExceptionHandler {

	@Resource
	private HttpServletRequest request;

	/**
	 * saToken权限不足
	 */
	@ExceptionHandler({NotPermissionException.class})
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R<String> notPermissionException(NotPermissionException exception) {
		log.warn("权限不足! {} -> {}", request.getRequestURI(), exception.getLocalizedMessage());
		return R.failed(null, "权限不足! ");
	}

	/**
	 * saToken未登录异常
	 */
	@ExceptionHandler({NotLoginException.class})
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R<String> notLoginException(NotLoginException exception) {
		log.warn("{} -> {}", request.getRequestURI(), exception.getLocalizedMessage());
		return R.failed(null, exception.getLocalizedMessage());
	}
}
